<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="用户ID" prop="userid">
        <el-input
          v-model="queryParams.userid"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="加密算法" prop="algorithm">
        <el-select v-model="queryParams.algorithm" placeholder="请选择算法" clearable>
          <el-option label="PBKDF2-SHA256" value="pbkdf2_sha256" />
          <el-option label="BCrypt" value="bcrypt" />
          <el-option label="SCrypt" value="scrypt" />
        </el-select>
      </el-form-item>
      <el-form-item label="修改时间" prop="lastChanged">
        <el-date-picker clearable
          v-model="queryParams.lastChanged"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:userPasswords:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:userPasswords:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:userPasswords:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:userPasswords:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="userPasswordsList" 
      @selection-change="handleSelectionChange"
      stripe
      border
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" width="80" />
      <el-table-column label="用户ID" align="center" prop="userid" width="100" />
      <el-table-column label="密码哈希" align="center" prop="passwordHash" min-width="200" show-overflow-tooltip>
        <template slot-scope="scope">
          <span style="font-family: monospace; font-size: 12px;">{{ scope.row.passwordHash }}</span>
        </template>
      </el-table-column>
      <el-table-column label="加密算法" align="center" prop="algorithm" width="150">
        <template slot-scope="scope">
          <el-tag type="success" size="small">{{ scope.row.algorithm }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="迭代次数" align="center" prop="iterations" width="100" />
      <el-table-column label="创建时间" align="center" prop="createdAt" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后修改" align="center" prop="lastChanged" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastChanged, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:userPasswords:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:userPasswords:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户密码对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="用户ID" prop="userid">
              <el-input v-model="form.userid" placeholder="请输入用户ID（关联users表）" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="密码哈希" prop="passwordHash">
              <el-input 
                v-model="form.passwordHash" 
                type="textarea"
                :rows="4"
                placeholder="请输入加密后的密码哈希值"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="盐值" prop="salt">
              <el-input 
                v-model="form.salt" 
                type="textarea"
                :rows="2"
                placeholder="请输入密码盐值（用于加密的随机字符串）"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="加密算法" prop="algorithm">
              <el-select v-model="form.algorithm" placeholder="请选择算法" style="width: 100%">
                <el-option label="PBKDF2-SHA256" value="pbkdf2_sha256" />
                <el-option label="BCrypt" value="bcrypt" />
                <el-option label="SCrypt" value="scrypt" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="迭代次数" prop="iterations">
              <el-input-number v-model="form.iterations" :min="10000" :step="10000" style="width: 100%" />
              <span class="form-tip">* 增加破解难度，建议260000次以上</span>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="最后修改时间" prop="lastChanged">
              <el-date-picker clearable style="width: 100%"
                v-model="form.lastChanged"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择最后修改密码时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUserPasswords, getUserPasswords, delUserPasswords, addUserPasswords, updateUserPasswords } from "@/api/system/userPasswords";

export default {
  name: "UserPasswords",
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      userPasswordsList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userid: null,
        passwordHash: null,
        salt: null,
        algorithm: null,
        iterations: null,
        createdAt: null,
        updatedAt: null,
        lastChanged: null
      },
      form: {},
      rules: {
        userid: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ],
        passwordHash: [
          { required: true, message: "密码哈希值不能为空", trigger: "blur" }
        ],
        salt: [
          { required: true, message: "密码盐值不能为空", trigger: "blur" }
        ],
        algorithm: [
          { required: true, message: "加密算法不能为空", trigger: "change" }
        ],
        iterations: [
          { required: true, message: "哈希迭代次数不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      listUserPasswords(this.queryParams).then(response => {
        this.userPasswordsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        id: null,
        userid: null,
        passwordHash: null,
        salt: null,
        algorithm: 'pbkdf2_sha256',
        iterations: 260000,
        createdAt: null,
        updatedAt: null,
        lastChanged: null
      };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户密码";
    },
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getUserPasswords(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改用户密码";
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateUserPasswords(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUserPasswords(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除用户密码编号为"' + ids + '"的数据项？').then(function() {
        return delUserPasswords(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleExport() {
      this.download('system/userPasswords/export', {
        ...this.queryParams
      }, `userPasswords_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.form-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
  margin-top: 4px;
  display: block;
}
</style>
